package com.tbit.uqbike.client.controller;

import com.tbit.uqbike.client.constant.RechargeConstant;
import com.tbit.uqbike.client.constant.ResponseCode;
import com.tbit.uqbike.client.constant.annotation.PreventDuplication;
import com.tbit.uqbike.client.exception.BaseException;
import com.tbit.uqbike.client.pojo.*;
import com.tbit.uqbike.client.pojo.newEntity.LeaderAccount;
import com.tbit.uqbike.client.pojo.vo.JsonResult;
import com.tbit.uqbike.client.service.*;
import com.tbit.uqbike.client.util.MD5PasswordUtil;
import com.tbit.uqbike.client.util.OrderNoUtil;
import com.tbit.uqbike.client.util.OutputUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;
import java.util.SortedMap;
import java.util.UUID;

/**
 * 支付分
 *
 * @Author: chen
 * @Description: 支付分
 * @Date: 创建于 17:43 2020/9/24
 */
@Controller
@RequestMapping("/payPoint")
public class PayPointController {

    @Autowired
    private TokenService tokenService;
    @Autowired
    private PayPointService payPointService;
    @Autowired
    private UserWxzffService userWxzffService;
    @Autowired
    private AdAccountFeeService adAccountFeeService;
    @Autowired
    private UserService userService;
    @Autowired
    private GiftCardUserService giftCardUserService;
    @Autowired
    private LeaderAccountService leaderAccountService;
    @Resource
    private RechargeService rechargeService;

    /**
     * 支付分授权界面
     *
     * @param token    令牌
     * @param session  会话
     * @param request  请求
     * @param response 响应
     */
    @RequestMapping("/leadData")
    public void leadData(String token, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            User user = tokenService.getUser(token);
            SortedMap<Object, Object> result = payPointService.leadData(user.getAccountId(), user.getUserId());
            //log.error("结果="+result);
            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, result);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);
    }

    /**
     * 支付分鉴权
     *
     * @param token
     * @param session
     * @param request
     * @param response
     */
    @RequestMapping("/auth")
    public void pre_authorization(String token, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            User user = tokenService.getUser(token);
            String result = payPointService.pre_authorization(user.getAccountId(), user.getUserId());
            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, result);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);
    }

    /**
     * 授权服务回调
     * 支付分回调
     * @param httpRequest
     * @return
     * @ignore
     */
    @RequestMapping("/callbackInform")
    public void callbackInform(HttpServletRequest httpRequest, HttpServletResponse response) {

        payPointService.callbackInform(httpRequest, response);
    }

    /**
     * 创建订单，需确认模式
     *
     * @param accountId 区域id
     * @param token     令牌
     * @param request   请求
     * @param response  响应
     */
    @RequestMapping("/create_zff_order")
    @PreventDuplication(expireSeconds = 5)
    public void create_zff_order(Integer accountId, String token, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            User user = tokenService.getUser(token);
            String result = payPointService.create_zff_order(accountId, user);
            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, result);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);
    }

    /**
     * 通过订单号获取支付分订单状态
     * @param orderNO
     */
    @RequestMapping("/getOrder")
    public void getOrder(String orderNO, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            Boolean result = payPointService.getOrderState(orderNO);
            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, result);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);
    }

    /**
     * 获取用户授权支付分状态
     *
     * @param token
     * @param adAccountId 区域id
     * @param request
     * @param response
     */
    @RequestMapping("/get_zff_status")
    public void get_zff_status(String token, Integer adAccountId, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            User user = tokenService.getUser(token);
            //Boolean result =payPointService.get_zff_status(user);
            Boolean result = false;
            UserWxzff userWxzff = userWxzffService.getByUserId(user.getUserId());
            if (userWxzff != null && userWxzff.getState().equals(RechargeConstant.WXZFF_AUTH)) {
                result = true;
            }
            if (adAccountId != null && !result) {
                User userDB = userService.getByUserId(user.getUserId());
                AdAccountFee adAccountFee = adAccountFeeService.getByAccountId(adAccountId, null);
                GiftCardUser giftCardUser = giftCardUserService.getByUserId(user.getUserId(), adAccountId);
                Integer gifMoney = 0;
                if (giftCardUser != null) {
                    gifMoney = giftCardUser.getMoney();
                }
                boolean isLeader = false;
                LeaderAccount leaderAccount = leaderAccountService.getByPhone(user.getPhone(),user.getAccountId());
                if (leaderAccount != null && System.currentTimeMillis() < leaderAccount.getExpireTime().getTime()) {
                    isLeader = true;
                }
                if (adAccountFee != null && userDB.getMoney() + gifMoney < adAccountFee.getRechargeBase() && !isLeader) {
                    map.put("money", adAccountFee.getRechargeBase() - userDB.getMoney() - gifMoney);
                }
            }
            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, result);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);
    }

    /**
     * 完结支付分订单,测试使用
     *
     * @param orderNO  订单编号
     * @param token
     * @param request
     * @param response
     */
    @RequestMapping("/finishOrder")
    public void finishOrder(String orderNO, String token, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            User user = tokenService.getUser(token);

            String serNO = UUID.randomUUID().toString();
            PayPoints payPoints = new PayPoints();
            payPoints.setAmount(0);
            payPoints.setName("骑行订单扣费");
            payPoints.setTotal_amount(0);
            payPoints.setOut_order_no(orderNO);
            payPointService.finishOrder(payPoints, user.getAccountId(), serNO, null, null, null);
            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, ResponseCode.SUCC);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);
    }

    /**
     * 网页人工结束订单
     *
     * @param userId   用户id
     * @param money    扣款金额
     * @param sign     签名
     * @param date     时间戳
     * @param param    附件参数
     * @param request
     * @param response
     */
    @RequestMapping("/outTime")
    public void finishOrderOutTime(Integer userId, Integer money, String sign, Long date, String param, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            boolean signCheck = MD5PasswordUtil.signCheck(sign, date, param);
            if (!signCheck) {
                throw new BaseException("-190002", "签名校验失败");
            }
            boolean result = payPointService.finishOrderOutTime(userId, money);
            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, result);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);
    }

    /**
     * 取消支付分订单
     *
     * @param token
     * @param request
     * @param response
     */
    @RequestMapping("/cancelOrder")
    public void cancelOrder(String token, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            User user = tokenService.getUser(token);
            payPointService.cancelOrder(user, "取消订单");
            map.put(ResponseCode.RET, ResponseCode.SUCC);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);
    }

    /**
     * 人工退款
     *
     * @param orderNO
     * @param refundMoney
     * @param token
     * @param request
     * @param response
     */
    @RequestMapping("/refund")
    public void refund(String orderNO, Integer refundMoney, String token, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            User user = tokenService.getUser(token);
            boolean result = payPointService.refund(orderNO, "人工处理", refundMoney, user, OrderNoUtil.getRefundNO());
            map.put(ResponseCode.RET, ResponseCode.SUCC);
            map.put(ResponseCode.DATA, result);
        } catch (BaseException e) {
            ResponseCode.printException(map, e, request);
        }
        OutputUtil.renderText(request, response, map);
    }
}
